﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc2Ng.Web.NgLib.Extensions.Attributes;
using System.Web.Mvc;
using Mvc2Ng.Web.UI.Models;
using Mvc2Ng.Web.UI.Code;

namespace Mvc2Ng.Web.UI.Controllers {

  /// <summary>
  /// An api that supports all datacontext calls from Angular SPA.
  /// </summary>
  [NgDataContext(typeof(DemoController), "DemoPortal/api")]
  public class DemoController : Api {

    # region Angular 

    public ActionResult GetAngularDataContext(){
      var dc =
      this.GetType()
          .GetCustomAttributes(typeof (NgDataContext), true)
          .OfType<NgDataContext>()
          .SingleOrDefault();
      if (dc != null){
        return JavaScript(dc.GetDataContext());
      }
      return null;
    }

    # endregion

    # region Messages

    [NgDataContextFunction]
    public JsonResult GetMessageCount() {
      return Json(72, JsonRequestBehavior.AllowGet);
    }

    [NgDataContextFunction]
    public JsonResult GetMessages() {
      return Json("", JsonRequestBehavior.AllowGet);
    }

    # endregion

    # region Project

    [NgDataContextFunction]
    public ActionResult GetProjects() {
      // we create some fake projects to let the UI running
      List<EaProject> result = new List<EaProject>();
      result.Add(new EaProject { Description = "Angular JS", Id = 1, IsPublished = false, Name = "NG", StartedAt = DateTime.Now });
      return JsonList(result, Math.Min(5, result.Count), JsonRequestBehavior.AllowGet);
    }

    [NgDataContextFunction]
    public ActionResult GetProjectsPublished() {
      List<EaProject> result = new List<EaProject>();
      result.Add(new EaProject { Description = "Angular JS", Id = 1, IsPublished = true, Name = "NG", StartedAt = DateTime.Now });
      return JsonList(result, Math.Min(5, result.Count), JsonRequestBehavior.AllowGet);
    }

    [NgDataContextFunction]
    public ActionResult GetProject(int id) {
      var result = new EaProject { Description = "Angular JS", Id = 1, IsPublished = true, Name = "NG", StartedAt = DateTime.Now };
      return Json(result, JsonRequestBehavior.AllowGet);
    }

    [NgDataContextFunction]
    [HttpPost]
    public ActionResult AddProject(EaProject p) {
      var project = p;
      if (project != null) {
        return Json(new { msg = String.Format("Project {0} created", project.Name) });
      } else {
        return new HttpStatusCodeResult(500, "Cannot create project");
      }
    }

    # endregion

    # region Helper

    private class EntityBaseIdentityComparer<T> : IEqualityComparer<T> where T : EaBase {

      public bool Equals(T x, T y) {
        return x.Id == y.Id;
      }

      public int GetHashCode(T obj) {
        return 0;
      }

    }

    # endregion

  }
}
